<template>
    <el-card shadow="never" header="修改邮箱">
        <el-alert title="邮箱更新成功后，您将被重定向到登录页面，您可以使用新邮箱重新登录。" type="warning" show-icon
                  style="margin-bottom: 15px;"/>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" style="margin-top:20px;">
            <el-form-item label="邮箱地址" prop="email">
                <el-input v-model="form.email" type="text" placeholder="请输入邮箱地址"></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="captcha">
                <div class="login-msg-yzm">
                    <el-input v-model="form.captcha" prefix-icon="Unlock" clearable
                              :placeholder="$t('login.emailPlaceholder')"></el-input>
                    <el-button @click="getCaptcha(formRef)" :disabled="disabled">
                        {{ $t('login.emailGet') }}
                        <span v-if="disabled">({{ countdown }})</span>
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit(formRef)">保存</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script setup lang="ts">
import {ref, reactive, nextTick} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, FormRules} from 'element-plus'
import {updateEmailApi} from "@/api/modules/auth.ts";
import {useAuthStore} from "@/store/modules/auth.ts";
import {useMenuStore} from "@/store/modules/menu.ts";
import {useSearchStore} from "@/store/modules/search.ts";
import {useEnvelopeStore} from "@/store/modules/envelope.ts";
import {useSysGlobalStore} from "@/store/system/global.ts";
import {useSysKeepAliveStore} from "@/store/system/keepAlive.ts";
import {useSysViewTagsStore} from "@/store/system/viewTags.ts";
import router from "@/router";
import {sendEmailCaptcha} from "@/api/modules/guest.ts";

interface FormData {
    email: string;
    captcha: string;
}

const form = reactive<FormData>({
    email: "",
    captcha: "",
})

const rules = reactive<FormRules<FormData>>({
    email: [
        {required: true, message: '请输入邮箱地址'}
    ],
    captcha: [
        {required: true, message: '请输入邮箱验证码'},
    ],
})

const disabled = ref(false);
const countdown = ref(0);
const getCaptcha = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validateField("email", async (valid) => {
        if (!valid) return;
        try {
            await sendEmailCaptcha({email: form.email});
            disabled.value = true;
            countdown.value = 60;
            const t = setInterval(() => {
                countdown.value -= 1;
                if (countdown.value < 1) {
                    clearInterval(t)
                    disabled.value = false;
                    countdown.value = 0;
                }
            }, 1000);
        } catch (error) {
            ElMessage.error("发送验证码失败，请重试！");
        }
    });
};

const formRef = ref<FormInstance>()
const submitting = ref(false);
const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    if (submitting.value) return;
    try {
        submitting.value = true;
        await formEl.validate();
        const updateData = await updateEmailApi(form);
        ElMessageBox.confirm(updateData.message, '提示', {
            type: 'success',
            confirmButtonClass: 'el-button--primary',
            showCancelButton: false,
        }).then(() => {
            useAuthStore().$reset();
            useMenuStore().$reset();
            useSearchStore().$reset();
            useEnvelopeStore().$reset();
            useSysGlobalStore().$reset();
            useSysKeepAliveStore().$reset();
            useSysViewTagsStore().$reset();
            nextTick(() => {
                router.replace({path: '/login'});
            });
        });
    } catch (error) {
        console.log(error);
    } finally {
        submitting.value = false;
    }
};
</script>
<style scoped>
.login-msg-yzm {
    display: flex;
    align-items: center;
    gap: 10px;
}

.login-msg-yzm .el-input {
    flex: 1;
}

.login-msg-yzm .el-button {
    white-space: nowrap;
}

</style>